<?php
// 小程序支付类
class xcxPayClass {
	
	private $WX_APPID;          //appid
    private $WX_SECRET;           //AppSecret
	private $WX_MCHID;          // mchid
	private $WX_MCPASS;          // mcpass
	
	public function __construct($appid,$appSecret,$mchid,$mcpass) {
		$this->WX_APPID = $appid;
		$this->WX_SECRET = $appSecret;
		$this->WX_MCHID = $mchid;
		$this->WX_MCPASS = $mcpass;
	}
	
	// 小程序获取登录用户
	public function login($code)
	{
		//获取openid
		if($code)
		{
			$WX_APPID = $this->WX_APPID;//appid
			$WX_SECRET = $this->WX_SECRET;//AppSecret
			$url = "https://api.weixin.qq.com/sns/jscode2session?appid=" . $WX_APPID . "&secret=" . $WX_SECRET . "&js_code=" . $code . "&grant_type=authorization_code";
			$infos = json_decode(file_get_contents($url));
			$data['openid'] = $infos->openid;
			
			echo json_encode($data);
		}
	}
	
	//处理微信支付回调
    public function notifydata($outdata)
	{
        $testxml  = file_get_contents("php://input");
        $jsonxml = json_encode(simplexml_load_string($testxml, 'SimpleXMLElement', LIBXML_NOCDATA));
        $result = json_decode($jsonxml, true);//转成数组
		
        if($result)
		{
            //如果成功返回了
			$result_sign = $result['sign'];
			unset($result['sign']);
			$sign = $this->sign($result);

            if($result_sign == $sign && $result['result_code'] == 'SUCCESS')
			{
				// 微信支付结果通知接口文档：https://pay.weixin.qq.com/wiki/doc/api/H5.php?chapter=9_7&index=8
				/*{
				  "appid": "12345",
				  "attach": "pay", 
				  "bank_type": "CFT",
				  "cash_fee": "1",
				  "fee_type": "CNY",
				  "is_subscribe": "Y",
				  "mch_id": "12345",
				  "nonce_str": "dZYFpaDYRpF5rwhv",
				  "openid": "onhwF1hiutUySKCsrV21A6MCtT5Q",
				  "out_trade_no": "SH201808222055598628",
				  "result_code": "SUCCESS",
				  "return_code": "SUCCESS",
				  "sign": "5A019F52BEF1C3A98AE0F1FF29D01574",
				  "time_end": "20180822205606",
				  "total_fee": "1",
				  "trade_type": "MWEB",
				  "transaction_id": "4200000171201808221550954201" 
				}*/
				
				// 商户订单号 out_trade_no
				// 订单金额 total_fee
				$ordersn = $result['out_trade_no']; 
				
				// 支付成功后修改状态
				// 执行业务逻辑改变订单状态等操作
				// 查询创建订单表 where("ordersn='".$out_trade_no."' and status=0") status为0表示待支付状态
				// 查询出来有该订单 就改变支付状态 status为1表示支付成功
				notifydatastatus($ordersn, $result, $outdata);
				
				//处理完成之后，告诉微信成功结果
				echo '<xml>
						  <return_code><![CDATA[SUCCESS]]></return_code>
						  <return_msg><![CDATA[OK]]></return_msg>
					  </xml>';
				exit();
            }else{
				echo '<xml>
						  <return_code><![CDATA[FAIL]]></return_code>
						  <return_msg><![CDATA[签名失败]]></return_msg>
					  </xml>';
				exit();	
			}
        }
    }
	
	//微信支付
	public function pay($paydata)
	{
		$fee = $paydata['price'];//举例支付0.01
		$appid = $this->WX_APPID;//appid.如果是公众号 就是公众号的appid
		$body = $paydata['title'];
		$mch_id = $this->WX_MCHID;//商户号
		$nonce_str = $this->nonce_str();//随机字符串
		$notify_url = 'https://www.jj1080.com/api/webview/notifydata.php'; //回调的url【自己填写】
		$openid = $paydata['openid'];
		$out_trade_no = $paydata['orderid'];//商户订单号 $this->order_number($openid)
		$spbill_create_ip = '';//服务器的ip【自己填写】;
		$total_fee = $fee*100;// 微信支付单位是分，所以这里需要*100
		$trade_type = 'JSAPI';//交易类型 默认
	 	
		// 报文数据
		//这里是按照顺序的 因为下面的签名是按照顺序 排序错误 肯定出错
		$post['appid'] = $appid;
		$post['body'] = $body;
		$post['mch_id'] = $mch_id;
		$post['nonce_str'] = $nonce_str;//随机字符串
		$post['notify_url'] = $notify_url;
		$post['openid'] = $openid;
		$post['out_trade_no'] = $out_trade_no;
		$post['spbill_create_ip'] = $spbill_create_ip;//终端的ip
		$post['total_fee'] = $total_fee;//总金额 
		$post['trade_type'] = $trade_type;
		$sign = $this->sign($post);//签名
		$post_xml = '<xml>
	           <appid>'.$appid.'</appid>
	           <body>'.$body.'</body>
	           <mch_id>'.$mch_id.'</mch_id>
	           <nonce_str>'.$nonce_str.'</nonce_str>
	           <notify_url>'.$notify_url.'</notify_url>
	           <openid>'.$openid.'</openid>
	           <out_trade_no>'.$out_trade_no.'</out_trade_no>
	           <spbill_create_ip>'.$spbill_create_ip.'</spbill_create_ip>
	           <total_fee>'.$total_fee.'</total_fee>
	           <trade_type>'.$trade_type.'</trade_type>
	           <sign>'.$sign.'</sign>
	        </xml> ';
	 	//print_r($post_xml);exit;
		
		//统一接口prepay_id
		$url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
		$xml = $this->http_request($url,$post_xml);
		$array = $this->xml($xml);//全要大写
		//print_r($array);
		
		// 创建订单成功
		if($array['RETURN_CODE'] == 'SUCCESS' && $array['RESULT_CODE'] == 'SUCCESS')
		{
			// 签名数据
			$time = time();
			$tmp=array();//临时数组用于签名
			$tmp['appId'] = $appid;
			$tmp['nonceStr'] = $nonce_str;
			$tmp['package'] = 'prepay_id='.$array['PREPAY_ID'];
			$tmp['signType'] = 'MD5';
			$tmp['timeStamp'] = "$time";
	 		
			// 接口参数
			$data['state'] = 200;
			$data['timeStamp'] = "$time";//时间戳
			$data['nonceStr'] = $nonce_str;//随机字符串
			$data['signType'] = 'MD5';//签名算法，暂支持 MD5
			$data['package'] = 'prepay_id='.$array['PREPAY_ID'];//统一下单接口返回的 prepay_id 参数值，提交格式如：prepay_id=*
			$data['paySign'] = $this->sign($tmp);//签名,具体签名方案参见微信公众号支付帮助文档;
			$data['out_trade_no'] = $out_trade_no;
	 
	 	// 创建失败
		}else{
			$data['state'] = 0;
			$data['text'] = "错误";
			$data['RETURN_CODE'] = $array['RETURN_CODE'];
			$data['RETURN_MSG'] = $array['RETURN_MSG'];
		}
	 
		echo json_encode($data);
	}
	
	//随机32位字符串
	private function nonce_str(){
		$result = '';
		$str = 'QWERTYUIOPASDFGHJKLZXVBNMqwertyuioplkjhgfdsamnbvcxz';
		for ($i=0;$i<32;$i++){
			$result .= $str[rand(0,48)];
		}
		return $result;
	}
	 
	//生成订单号
	private function order_number($openid){
		//date('Ymd',time()).time().rand(10,99);//18位
		return md5($openid.time().rand(10,99));//32位
	}

	//签名 $data要先排好顺序
	private function sign($data){
		$stringA = '';
		foreach ($data as $key=>$value){
		if(!$value) continue;
			if($stringA) $stringA .= '&'.$key."=".$value;
			else $stringA = $key."=".$value;
		}
		$wx_key =$this->WX_MCPASS;//申请支付后有给予一个商户账号和密码，登陆后自己设置的key
		$stringSignTemp = $stringA.'&key='.$wx_key;
		return strtoupper(md5($stringSignTemp));
	}

	//curl请求
	public function http_request($url,$data = null,$headers=array())
	{
		$curl = curl_init();
		if( count($headers) >= 1 ){
			curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
		}
		curl_setopt($curl, CURLOPT_URL, $url);
	 
	 
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
	 
	 
		if (!empty($data)){
			curl_setopt($curl, CURLOPT_POST, 1);
			curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
		}
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		$output = curl_exec($curl);
		curl_close($curl);
		return $output;
	}
	 
	//获取xml
	private function xml($xml){
		$p = xml_parser_create();
		xml_parse_into_struct($p, $xml, $vals, $index);
		xml_parser_free($p);
		$data = "";
		foreach ($index as $key=>$value) {
			if($key == 'xml' || $key == 'XML') continue;
			$tag = $vals[$value[0]]['tag'];
			$value = $vals[$value[0]]['value'];
			$data[$tag] = $value;
		}
		return $data;
	}
}